package com.xzy.demo.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ProductName: Hundsun HEP
 * @ProjectName: demo
 * @Package: com.xzy.demo.juc
 * @Description:
 * @Author: xiaozy37528
 * @CreateDate: 2021/8/17 15:30
 * @UpdateUser: xiaozy37528
 * @UpdateDate: 2021/8/17 15:30
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>
 * Copyright © 2021 Hundsun Technologies Inc. All Rights Reserved
 **/
public class CountDownLatchDemo {
    private static CountDownLatch countDownLatch = new CountDownLatch(20);

    private static ReentrantLock reentrantLock = new ReentrantLock();

    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = reentrantReadWriteLock.readLock();
    private static Lock writeLock = reentrantReadWriteLock.writeLock();

    public static void readHandle(Lock lock) {
        lock.lock();
        try {
            // do something
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + " read");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            countDownLatch.countDown();
        }
    }

    public static void writeHandle(Lock lock) {
        lock.lock();
        try {
            // do something
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + " write");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 18; i++) {
            executorService.submit(() -> readHandle(readLock));
        }
        for (int i = 0; i < 2; i++) {
            executorService.submit(() -> writeHandle(writeLock));
        }


        countDownLatch.await();
        System.out.println("执行时间：" + (System.currentTimeMillis() - start));

        executorService.shutdown();
    }
}
